Categories
Node.js Best Practices

Node.js Best Practices — REST and Test

Spread the love

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing Node apps.

Use HTTP Methods & API Routes

We should follow RESTful conventions when we create our endpoints.

We should use nouns as identifiers.

For example, we have routes like:

  • POST /article or PUT /article/:id to create a new article
  • GET /article to retrieve a list of articles
  • GET /article/:id to retrieve an article
  • PATCH /article/:id to modify an existing article
  • DELETE /article/:id to remove an article

Use HTTP Status Codes Correctly

Status codes should correctly tell the status of our response.

We can have the following:

  • 2xx, if everything is fine.
  • 3xx, if the resource has moved
  • 4xx, if the request can’t be fulfilled because of a client error
  • 5xx, if something went wrong on the API side.

Client-side errors are things like invalid input or unauthorized credentials.

Server-side errors are things like exceptions thrown on the server-side for whatever reasons.

We can respond with status codes in Express with res.status .

For example, we can write:

res.status(500).send({ error: 'an error occurred' })

We respond with the 500 status code with a message.

Use HTTP headers to Send Metadata

HTTP headers let us send metadata with requests and responses.

They can include information like pagination, rate-limiting, or authentication.

We can add custom headers by prefixing the keys with X- .

For instance, we can send a CSRF token with the X-Csrf-Token request header.

HTTP doesn’t define any size limit on headers.

However, Node imposes an 80KB limit as the max heart size.

The Right Framework for Our Node.js REST API

We should pick the right framework for our REST API.

There’s Koa, Express, Hapi, Resify, Nest.js, and more.

We can use the first 4 to build simple rest services.

If we need a more complete solution, we can use Nest.js.

It has things like ORM and testing built-in.

Black-Box Test Our Node.js REST APIs

To test our Node REST APIs, we can make requests to our API and check the results.

We can use a specialized HTTP client like Supertest to test our API.

For example, to test getting an article with it, we can write:

const request = require('supertest')

describe('GET /user/:id', () => {
  it('returns a user', () => {
    return request(app)
      .get('/article')
      .set('Accept', 'application/json')
      .expect(200, {
        id: '1',
        title: 'title',
        content: 'something'
      }, done)
  })
})

We make the HTTP request to the article endpoint.

And we call set to set some request headers.

Then we call expect to check the status code and response body respectively.

The data would be populated in a database that’s only used when running unit tests.

They would be reset after every test.

This ensures that we have clean data to test with.

In addition to black-box tests, we should also do unit tests for other parts like the services.

Conclusion

We should follow RESTful conventions for our APIs.

Also, testing is important for any app.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *